<template>
  <div>
    <div>
      <el-button type="primary" @click="addUser">增加用户</el-button>
    </div>
    <div>
      <br />
      <el-input v-model="chkUser.name" placeholder="请输入名字" style="width: 220px;"></el-input>
      <el-button type="primary" @click="getUserList">查询用户</el-button>
    </div>
    <div>
      <el-table :data="userList" style="width: 100% height: 10" stripe class="user-container">
        <el-table-column prop="name" label="姓名" width="180" height="50px"></el-table-column>

        <el-table-column prop="phone" label="手机" width="180"></el-table-column>

        <el-table-column prop="telephone" label="座机" width="180"></el-table-column>

        <el-table-column prop="address" label="地址" width="180"></el-table-column>

        <el-table-column prop="enabled" label="状态" width="150" :formatter="formSex"></el-table-column>

        <el-table-column prop="username" label="登录名" width="150"></el-table-column>

        <el-table-column prop="upic" label="图片" width="200">
          <template slot-scope="scope">
            <img :src="scope.row.userface" style="width: 120px; height: 80px;" />
          </template>
        </el-table-column>

        <el-table-column label="操作" width="500">
          <template slot-scope="scope">
            <el-button type="danger" round @click="setTwicePassword(scope.row)">重置密码</el-button>
            <el-button type="primary" round @click="upUserFace(scope.row)">上传图片</el-button>
            <el-button type="primary" round @click="setRole(scope.row)">给我力量</el-button>
            <el-button type="danger" round @click="del(scope.row)">禁用</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div>
      <el-pagination
        @current-change="getUserList"
        background
        :current-page="pageInfo.current"
        :page-count="pageInfo.pages"
      ></el-pagination>
    </div>
    <!-- ======================================================增加================================================= -->
    <div>
      <el-dialog title="添加" :visible.sync="dialogVisible" width="30%" class="user-dialogVisible">
        <el-form
          ref="userForm"
          :model="userForm"
          label-width="80px"
          :rules="rules"
          label-position="left"
        >
          <el-form-item label="真实名称" prop="name">
            <el-input v-model="userForm.name"></el-input>
          </el-form-item>

          <el-form-item label="手机号码" prop="phone">
            <el-input v-model="userForm.phone" auto-complete="off"></el-input>
          </el-form-item>

          <el-form-item label="座机">
            <el-input v-model="userForm.telephone"></el-input>
          </el-form-item>

          <el-form-item label="地址">
            <el-input v-model="userForm.address"></el-input>
          </el-form-item>

          <el-form-item label="登录名称" prop="username">
            <el-input v-model="userForm.username"></el-input>
          </el-form-item>

          <el-form-item label="密码" prop="password">
            <el-input v-model="userForm.password" auto-complete="off"></el-input>
          </el-form-item>

          <el-form-item label="确认密码" prop="checkPass">
            <el-input v-model="checkPass" autocomplete="off"></el-input>
          </el-form-item>

          <el-form-item label="状态">
            <el-radio-group v-model="userForm.enabled" size="medium">
              <el-radio border label="1">启用</el-radio>
              <el-radio border label="2">暂不启用</el-radio>
            </el-radio-group>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" @click="doAddUser">立即创建</el-button>
            <el-button @click="outAdd">取消</el-button>
          </el-form-item>
        </el-form>
      </el-dialog>
    </div>

    <div>
      <!-- ======================================================授权================================================= -->
      <el-dialog title="授权" :visible.sync="dialogVisibles" width="40%" class="user-dialogVisible">
        <el-button type="success" @click="restRole">重新授权</el-button>

        <el-table :data="RoleList" stripe style="width: 100%">
          <el-table-column prop="name" label="登录角色名" width="180"></el-table-column>
          <el-table-column prop="nameZh" label="登录姓名" width="180"></el-table-column>
          <el-table-column label="操作" width="300">
            <template slot-scope="scope">
              <el-button type="primary" round @click="passThis(scope.row)">走开</el-button>
            </template>
          </el-table-column>
        </el-table>

        <span slot="footer" class="dialog-footer">
          <el-button @click="disDialogVisibles">取 消</el-button>
          <el-button type="primary" @click="dialogVisibles = false">确 定</el-button>
        </span>
      </el-dialog>
    </div>

    <!-- ======================================================重新授权================================================= -->
    <div>
      <el-dialog title="重新授权" :visible.sync="dialogVisibleb" width="30%" class="user-dialogVisible">
        <el-table
          :data="AllRoleList"
          stripe
          style="width: 100%"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55"></el-table-column>
          <el-table-column prop="name" label="登录角色名" width="180"></el-table-column>
          <el-table-column prop="nameZh" label="登录姓名" width="180"></el-table-column>
        </el-table>
        <div>
          <el-pagination
            @current-change="restRole"
            background
            :current-page="AllRolePageInfo.current"
            :page-count="AllRolePageInfo.pages"
          ></el-pagination>
        </div>

        <span slot="footer" class="dialog-footer">
          <el-button @click="disDialogVisibleb">取 消</el-button>
          <el-button type="primary" @click="PushRole">确 定</el-button>
        </span>
      </el-dialog>
    </div>
    <!------------------------------------------上传图片----------------------------------->
    <div>
      <el-dialog title="上传图片" :visible.sync="dialogVisiblec" width="30%" class="user-dialogVisible">
        <input type="file" class="file" />
        <el-button type="primary" @click="doUpUserface">上传</el-button>
      </el-dialog>
    </div>
  </div>
</template>
<script>
import axios from "axios";

export default {
  inject: ["reload"],
  data() {
    var validatePass2 = (rule, value, callback) => {
      if (this.checkPass === "") {
        callback(new Error("请再次输入密码"));
      } else if (this.checkPass !== this.userForm.password) {
        callback(new Error("两次输入密码不一致!"));
      } else {
        callback();
      }
    };
    var validateName = (rule, value, callback) => {
      this.$ajax({
        method: "get",
        url: "http://localhost:8081/user/selectUserByUsername/" + value + ""
      }).then(res => {
        if (value == "") {
          callback(new Error("用户名已存在"));
        } else if (res.data.object >= 1) {
          callback(new Error("用户名已存在"));
        } else {
          callback();
        }
      });
    };
    var checkPhone = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("手机号不能为空"));
      } else {
        const reg = /^1[3|4|5|7|8][0-9]\d{8}$/;
        console.log(reg.test(value));
        if (reg.test(value)) {
          callback();
        } else {
          return callback(new Error("请输入正确的手机号"));
        }
      }
    };

    return {
      chkUser: {},
      userList: [],
      pageInfo: {},
      dialogVisible: false,
      userForm: {},
      checkPass: "",
      rules: {
        username: [
          { required: true, validator: validateName, trigger: "blur" },
          { min: 3, max: 10, message: "长度在 3 到 10 个字符", trigger: "blur" }
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          { min: 3, max: 10, message: "长度在 3 到 10 个字符", trigger: "blur" }
        ],
        checkPass: [
          { required: true, validator: validatePass2, trigger: "blur" }
        ],
        phone: [{ required: true, validator: checkPhone, trigger: "blur" }]
      },
      dialogVisibles: false,
      RoleList: [],
      uid: "",
      dialogVisibleb: false,
      AllRoleList: [],
      multipleSelection: [],
      AllRolePageInfo: {},
      dialogVisiblec: false,
      upPic: {
        id:""
      }
    };
  },
  mounted: function() {
    this.getUserList();
  },
  methods: {
    getUserList: function(page) {
      if (page == undefined || page == null) {
        page = 0;
      }
      var wmh = this;

      var url = "http://localhost:8081/user/page?pageNum=" + page + "&pageSize=4";
    //  var url = "http://localhost:8081/user/getUserInfoList?pageIndex=" + page + "&pageSize=4";
      // if(wmh.chkUser.name!=undefined && wmh.chkUser.name!=null){
      //   url = "http://localhost:8081/user/page?pageNum=" + page + "&pageSize=5&name="+wmh.chkUser.name;
      // }

      wmh
        .$ajax({
          url: url,
          method: "get"
        })
        .then(function(res) {
          if (res.data.code == 200) {
            wmh.userList = res.data.object.records;
            wmh.pageInfo = res.data.object;
          }
        });
    },
    addUser: function() {
      this.dialogVisible = true;
    },
    doAddUser: function() {
      var wmh = this;
      wmh
        .$ajax({
          url: "http://localhost:8081/user/insert",
          method: "post",
          params: wmh.userForm
        })
        .then(function(res) {
          wmh.dialogVisible = false;
          if (res.data.msg == "增加成功") {
            wmh.$message(res.data.msg);
            wmh.reload();
            wmh.getUserList();
          }
        });
    },
    del: function(res) {
      var wmh = this;
      wmh
        .$ajax({
          url:
            "http://localhost:8081/user/setEnabled/" +
            res.id +
            "/" +
            res.enabled +
            "",
          method: "put"
        })
        .then(function(res) {
          if (res.data.msg == "禁用成功") {
            wmh.getUserList();
          }
        });
    },
    outAdd: function() {
      this.dialogVisible = false;
      this.userForm = {};
      this.checkPass = "";
    },
    formSex: function(row, column, cellValue) {
      if (cellValue == "1") {
        return "启用中";
      } else if (cellValue == "2") {
        return "禁用中";
      }
    },
    passThis: function(res) {
      this.RoleList = [];
      var wmh = this;
      wmh
        .$ajax({
          url:
            "http://localhost:8081/user/deleteMenuRoleByUidAndRid?id=" +
            wmh.uid +
            "&rid=" +
            res.id,
          method: "delete"
        })
        .then(function(obj) {
          if (obj.data.msg == "取消成功") {
            alert("成功");
            wmh.$message(obj.data.msg);
            wmh.RoleList = {};
            // wmh.reload();
          }
        });
    },
    setRole: function(res) {
      var wmh = this;
      wmh.RoleList = [];
      wmh.dialogVisibles = true;
      wmh
        .$ajax({
          url: "http://localhost:8081/user/getRoleByUid?id=" + res.id,
          method: "get"
        })
        .then(function(obj) {
          if (obj.data.msg == "查询成功") {
            wmh.RoleList = obj.data.object;
            wmh.uid = res.id;
          }
        });
    },
    restRole: function(p) {
      var wmh = this;
      wmh.AllRolePageInfo = {};
      wmh.AllRoleList = [];
      var page = 0;
      wmh.dialogVisibleb = true;
      if (p != undefined && p != null && p > 0) {
        page = p;
      }
      wmh
        .$ajax({
          url:
            "http://localhost:8081/role/page?pageNum=" + page + "&pageSize=4",
          method: "get"
        })
        .then(function(res) {
          if (res.data.code == 200) {
            wmh.AllRolePageInfo = res.data.object;
            wmh.AllRoleList = res.data.object.records;
          }
        });
    },
    PushRole: function() {
      var wmh = this;

      var rids = new Array();
      for (var i = 0; i < wmh.multipleSelection.length; i++) {
        rids.push(wmh.multipleSelection[i].id);
      }

      axios
        .get(
          "http://localhost:8081/user/setUserRole?rids=" +
            rids +
            "&id=" +
            wmh.uid
        )
        .then(function(arr) {
          if (arr.data.code == 200) {
            alert("成功");
            wmh.dialogVisibleb = false;
            wmh.dialogVisibles = false;
            wmh.dialogVisibles = true;
          } else {
            alert("失败");
          }
        });

      // wmh
      //   .$ajax({
      //     url: "http://localhost:8081/user/setUserRole",
      //     method: "put",
      //     params: {rids:rids,uid:wmh.uid}
      //   })
      //   .then(function(obj) {
      //     if(obj.data.code==200){
      //       alert(obj.data.msg)
      //       wmh.disDialogVisibleb=false;
      //     }

      //   });
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    disDialogVisibleb: function() {
      this.dialogVisibleb = false;
    },
    disDialogVisibles: function() {
      this.dialogVisibles = false;
      this.uid = "";
    },
    upUserFace: function(user) {
      this.dialogVisiblec = true;
      this.upPic.id=user.id
    },
    doUpUserface: function() {
      var hao = this;
      var formData = new window.FormData();
      formData.append(
        "file",
        document.querySelector("input[type=file]").files[0]
      );
      var options = {
        url: "http://localhost:8081/user/upUserFace/"+hao.upPic.id+"",
        data: formData,
        method: "post",
        headers: {
          "Content-type": "multipart/form-data"
        }
      };
      axios(options).then(function(arr) {
        if(arr.data.msg){
          alert("成功")
          hao.dialogVisiblec=false;
          hao.getUserList(1);
          hao.upPic.id="";
        }
        
      });
    },
    disUpload: function() {
      this.dialogVisiblec = false;
      this.upPic.id="";
    },
    setTwicePassword:function(user){
      var wmh = this;

      axios
        .get("http://localhost:8081/user/setNewPassword/"+user.username)
        .then(function(arr) {
          if (arr.data.code == 200) {
            alert("成功");
          } else {
            alert("失败");
          }
        });
    }
  }
};
</script>
<style>
.user-container {
  opacity: 0.6;
}
.user-dialogVisible {
  opacity: 0.8;
}
</style>